import React, { useState, useEffect, useRef } from 'react';
import MyModal from './MyModal';
import './modal.css';
import styles from './myHooks.module.css';

export default function MyHooks() {
  const modalRef = useRef(null);

  const [showModal, setShowModal] = useState(false);

  // 点击是否开始滚动
  const handleShowModal = e => {
    const headDom = document.getElementsByTagName('head')[0];
    const getStyle = headDom.getElementsByTagName('style');
    for (const s of getStyle) {
      if (s.getAttribute('data-rc-order') === 'append') {
        // console.log(s, 's');
        s.remove();
      }
    }
    // console.log(e, e?.target)
    if (e && e.target) {
      if (!showModal) {
        const styleDom = document.createElement('style');
        styleDom.dataset.rcOrder = 'append';
        styleDom.innerHTML = 'html body { overflow-y: hidden; height: calc(100% - 200px) }';
        headDom.appendChild(styleDom);
        // console.log('modalRef', modalRef);
      }
      setShowModal(!showModal);
    } else {
      setShowModal(false);
    }
  };

  useEffect(() => {
    return () => {
      // 退出页面打开页面滚动
      handleShowModal();
    };
  }, []);

  return (
    <div className={styles.wrap}>
      <span>MyHooks demo 234</span>
      <div>
        <Modal />
      </div>
      <div>
        <span className={styles.modal} onClick={handleShowModal}>
          <i className='iconfont icon-xiazai4'></i>
          <span>弹窗</span>
        </span>
        <MyModal ref={modalRef} show={showModal} handleShowModal={handleShowModal} />
        <ul style={{ display: 'flex', flexDirection: 'column' }}>
          {Array.from({ length: 50 }, (_, i) => (
            <li key={i}>{i}</li>
          ))}
        </ul>
      </div>
    </div>
  );
}

export function Modal() {
  const [showModal, setShowModal] = useState(false);

  const toggleModal = () => {
    setShowModal(!showModal);
  };

  return (
    <div>
      <button onClick={toggleModal}>Toggle Modal</button>
      <div className={`modal ${showModal ? 'show' : ''}`} onClick={toggleModal}>
        <div className='modal-content' onClick={e => e.stopPropagation()}>
          <h1>Modal Title</h1>
          <p>This is the content of the modal.</p>
        </div>
      </div>
    </div>
  );
}
